import { defineStore } from 'pinia'
import http from '@/libs/http.js'
import { deleteUser,getAllUsers } from '@/apis/admin/api.js'
export const useAdminStore = defineStore('admin', {
  state: () => ({
    users: [],
    total: 0,
    currentPage: 1,
    pageSize: 10
  }),

  actions: {
    // 获取所有用户
    async fetchUsers() {
      try {
        const data = await getAllUsers()
        this.users = data
        return data
      } catch (error) {
        throw new Error('Failed to fetch users')
      }
    },

    // 删除单个用户
    async deleteUser(username) {
      try {
        await deleteUser(username)
        // await this.fetchUsers()
      } catch (error) {
        throw new Error('Failed to delete user')
      }
    },

    async toggleUserStatus(userId, status) {
      try {
        await http.put(`/api/admin/users/${userId}/status`, {
          status: status
        })
        await this.fetchUsers()
      } catch (error) {
        throw new Error('Failed to update user status')
      }
    },

    async resetUserPassword(userId) {
      try {
        await http.post(`/api/admin/users/${userId}/reset-password`)
      } catch (error) {
        throw new Error('Failed to reset password')
      }
    },

    setPageInfo(page, size) {
      this.currentPage = page
      this.pageSize = size
    }
  },

  getters: {
    filteredUsers: (state) => (searchQuery) => {
      if (!searchQuery) return state.users
      
      return state.users.filter(user => 
        user.username.toLowerCase().includes(searchQuery.toLowerCase()) ||
        user.email.toLowerCase().includes(searchQuery.toLowerCase())
      )
    }
  }
})
